package com.atguigu.rabbitmq.simple;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * Consumer
 *
 * @Author: 马伟奇
 * @CreateTime: 2021-02-24
 * @Description:
 */
public class Consumer {
    public static void main(String[] args) throws Exception{
        //  设置数据源
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare("simple_queue",
                true,
                false,
                false,
                null);

        DefaultConsumer consumer = new DefaultConsumer(channel){
            // ctrl + o：实现没有实现的方法

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("consumerTag:" + consumerTag);
                System.out.println("Exchange:" + envelope.getExchange());
                System.out.println("RoutingKey:" + envelope.getRoutingKey());
                System.out.println("properties:" + properties);
                System.out.println("body:"+ new String(body));
            }
        };

        // 监听消息
        // 第一个参数表示需要监听的队列
//        String queue, :表示队列的名字
// boolean autoAck, ：是否签收确认
// Consumer callback
        channel.basicConsume("simple_queue",true,consumer);
        // 不要关闭监听器
    }
}